<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    const obj = {
      a: 1,
      b: {m: 2},
      c: [1, 2],
      d () {}
    }
    obj.b.n = obj.c
    obj.c[2] = obj.b

    /* 
    方式一: 利用JSON对象
    问题1: 函数属性丢失  => 原因: json字符串中没有函数
    问题2: 有循环引用报错 => 原因: 在转json字符串时死循环
    */
    function cloneDeep(target) {
      return JSON.parse(JSON.stringify(target))
    }

    console.log(cloneDeep(obj))


    // 得到数据类型
    function getType(target) {
      return Object.prototype.toString.call(target).slice(8, -1);
    }           

    /* 
    方式二: 递归遍历拷贝
    解决了问题1, 还有问题2
    */
    function cloneDeep2(target) {
      const type = getType(target)
      if (type==='Object' || type==='Array') {
        let cloneTarget
        if (type==='Object') {
          cloneTarget = {}
          Object.keys(target).forEach(key => {
            cloneTarget[key] = cloneDeep2(target[key])
          })
        } else {
          cloneTarget = []
          target.forEach(item => {
            cloneTarget.push(cloneDeep2(item))
          })
        }
        return cloneTarget
      }

      return target

    }

    // console.log(cloneDeep2(obj))


    /* 
    方式二: 递归遍历拷贝
    解决了问题1, 还有问题2
    */
    function cloneDeep3(target, map=new Map()) {
      const type = getType(target)
      if (type==='Object' || type==='Array') {
        // 在准备创建新的clone对象时, 先从map缓存中读取缓存的clone对象, 如果有直接返回, 如果没有创建一个新的, 并保存map中
        let cloneTarget = map.get(target)
        if (cloneTarget) return cloneTarget
        if (type==='Object') {
          cloneTarget = {}
          map.set(target, cloneTarget)
          Object.keys(target).forEach(key => {
            cloneTarget[key] = cloneDeep3(target[key], map) // 递归调用时传递map
          })
        } else {
          cloneTarget = []
          map.set(target, cloneTarget)
          target.forEach(item => {
            cloneTarget.push(cloneDeep3(item, map)) // 递归调用时传递map
          })
        }
        return cloneTarget
      }

      return target

    }

    // console.log(cloneDeep3(obj))
  </script>
</body>
</html>